# Copyright (c) 2010, College Center for Library Automation

# See the included Copyright.txt file for full license

#
use strict;
use warnings;
#use PDF::ReportWriter;

require "ReportWriter150.pm";
use avsCommon;

use DBI;
use DBD::ODBC;
use Date::Calc qw(Decode_Month Today Month_to_Text Add_Delta_YM );

my ($dbhstats, $sqlstats, $sthstats);

my @dbdata = ();

$dbhstats = DBI->connect('dbi:ODBC:AutomatedVendorStats' ,,, { 'PrintError' => 1, 'RaiseError' => 1 })
	or die '#error: dbhlogin connect: ' . DBI->errstr;
#	
paramscheck();

# fetch new datasources
$sqlstats = qq/SELECT     Source, CONVERT(VARCHAR, AddDate, 101) AS TheDate
FROM         View_DataSourceVendor
WHERE     (AddDate >= CONVERT(DATETIME, ?, 102))
ORDER BY Source/;

$sthstats = $dbhstats->prepare($sqlstats)
	or die '#error: sthstats prepare: ' . DBI->errstr;

# prepare to build a csv file after pdf file
use Text::CSV;
my $csv=Text::CSV->new();

$sthstats->execute(join('-', @begdate));

setupXML();

@dbdata = @{$sthstats->fetchall_arrayref()};

my $rw = PDF::ReportWriter->new();
$rw->render_report("../temp/Rpt_new_datasources.tmp",  \@dbdata);
$rw->{destination}="../Reports/new_datasources_$begdate[0]_$begdate[1].pdf";
$rw->save();

# open and send data to the csv file
open CSV, ">../Reports/new_datasources_$begdate[0]_$begdate[1].csv";
print CSV '"Vendor Data Source",Type,',"\n";

foreach my $datarow (@dbdata) {
	if ($csv->combine(@{$datarow})) {
		print CSV $csv->string(),"\n";
	}
}

close CSV;

$sthstats->finish if ($sthstats);
$dbhstats->disconnect if ($dbhstats);

sub setupXML {
	use XML::Twig;
	use IO::File;

	my $file = 'Rpt_new_datasources.xml';
	my $twig= new XML::Twig(
		TwigHandlers => {
			'page/header/cell[@name="month"]' => \&heading_handler_months,
			'page/header/cell[@name="rundate"]' => \&heading_handler_rundate},
		TwigRoots => {report => 1});
	$twig->parsefile($file);

	my $fh = new IO::File("../temp/Rpt_new_datasources.tmp", "w");
	$twig->print($fh);
	close $fh;

	# put the run date in header
	sub heading_handler_rundate {
		my ($twig_obj, $rundate_cell) = @_;
		my ($tyear,$tmonth,$tday) = @begdate;
		$rundate_cell->first_child('text')->set_text(Month_to_Text($tmonth).' '.$tday.', '.$tyear);
	}

}
